package com.fm.magic.net.proxy;

import com.fm.base.database.DBClient;
import com.fm.base.database.DBDataFilter;
import com.fm.base.database.domain.DBSortedDocument;
import com.fm.magic.Factory;
import com.fm.mongodb.client.service.SimpleDomainService;
import org.bson.Document;
import org.joda.time.DateTime;

import java.util.Collection;
import java.util.Date;

public class ProxyRepertory {
    public static void update(Collection<ProxyCollector.ProxyInfo> proxiesInfo) {
        Date date = new Date();
        try (DBClient client = Factory.getLocalProxiesDB()) {
            SimpleDomainService<DBSortedDocument> domain = (SimpleDomainService<DBSortedDocument>) client.getDomainService("ProxiesGrab", DBSortedDocument.class);
            proxiesInfo.forEach(proxyInfo -> {
                String id = proxyInfo.host + ":" + proxyInfo.port;
                DBSortedDocument document = domain.search(DBDataFilter.equal("_id", id));
                DateTime now = DateTime.now();
                if (document == null) {
                    DBSortedDocument save = new DBSortedDocument();
                    save.put("_id", id);
                    save.put("host", proxyInfo.host);
                    save.put("port", proxyInfo.port);
                    save.put("location", proxyInfo.location);
                    save.put("type", proxyInfo.type.name());
                    save.put("websites", new DBSortedDocument().append(proxyInfo.website.name(), date));
                    save.put("createTime", now);
                    save.put("updateTime", now);
                    domain.insert(save);
                } else {
                    Document update = new Document();
                    update.put("location", proxyInfo.location);
                    update.put("type", proxyInfo.type.name());
                    update.put("websites." + proxyInfo.website.name(), date);
                    update.put("updateTime", now);
                    domain.update(
                        new Document("_id", id),
                        new Document("$set", update),
                        false);
                }
            });
        }
    }
}
